import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/login/protocol.dart';
import 'package:studymanage/mine/about_us.dart';
import 'package:studymanage/mine/personal.dart';
import 'package:studymanage/util/request.dart';

import 'my_course.dart';
import 'my_share.dart';

class Mine extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MineState();
  }
}

class MineState extends State{
  Map _userInfo = {};
  String _cacheSizeStr="0";
  @override
  void initState() {
    Request().post<Map<String,dynamic>>("/multiapi/c203v_userData").then((response){
      if(response.code == 200){
        setState(() {
          _userInfo = response.data;
        });
      }else{
        _userInfo = {};
      }
    });
    loadCache();
    super.initState();
  }
  ///加载缓存
  Future<Null> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
//      tempDir.list(followLinks: false,recursive: true).listen((file){
//      });
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSizeStr = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

  void _clearCache() async {
    Directory tempDir = await getTemporaryDirectory();
    if (tempDir is Directory) {
      final List<FileSystemEntity> children = tempDir.listSync();
      for (final FileSystemEntity child in children) {
        child.delete(recursive: true);
      }
    }
    double value = await _getTotalSizeOfFilesInDir(tempDir);
//      tempDir.list(followLinks: false,recursive: true).listen((file){
//      });
    print('临时目录大小: ' + value.toString());
    setState(() {
      _cacheSizeStr = _renderSize(value);
    });
    Request().toast('清除缓存成功');
  }
  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    await file.delete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0XFFf8f8f8),
      body: SingleChildScrollView(
        child: Stack(
          alignment: Alignment.topCenter,
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width,
              child: Column(
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width,
                    height: ScreenUtil().setHeight(230),
                    padding: EdgeInsets.only(
                      top: ScreenUtil().setHeight(85),
                    ),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/mine/mine_bg.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Column(
                      children: <Widget>[
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            border: Border.all(
                              color: Colors.white,
                              width: ScreenUtil().setHeight(2),
                            ),
                            borderRadius: BorderRadius.circular(ScreenUtil().setHeight(39)),
                          ),
                          child: CircleAvatar(
                            radius: ScreenUtil().setHeight(38),
                            backgroundImage:_userInfo['avatar']==null ? Image.asset("assets/images/mine/mine_bg.png").image : NetworkImage(_userInfo['avatar']),
                            backgroundColor: Colors.transparent,
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(12),
                          ),
                          child: Text(_userInfo['nickname']==null ? "加载中" : _userInfo['nickname'],
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Medium',
                              fontSize: ScreenUtil().setSp(14),
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        Offstage(
                          offstage: Global.profile.userTypeEnum == 1,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Offstage(
                                offstage: _userInfo['level'] == null,
                                child: Container(
                                  margin: EdgeInsets.only(
                                    top: 5
                                  ),
                                  padding: EdgeInsets.all(3),
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.white,width: 1),
                                    borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: Text(_userInfo['level']!=null ? _userInfo['level'] : '',
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setSp(11),
                                      fontWeight: FontWeight.w400,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                              Offstage(
                                offstage: _userInfo['nextLevel'] ==null,
                                child: Container(
                                  margin: EdgeInsets.only(
                                    top: 10,
                                    left: 10
                                  ),
                                  child: Text("下一个等级: "+(_userInfo['nextLevel']!=null ? _userInfo['nextLevel'] : "") ,
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setSp(11),
                                      fontWeight: FontWeight.w400,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Offstage(
                          offstage: Global.profile.userTypeEnum == 2,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Offstage(
                                offstage:_userInfo['className']==null,
                                child: Container(
                                  margin: EdgeInsets.only(
                                      top: 5
                                  ),
                                  padding: EdgeInsets.all(3),
                                  decoration: BoxDecoration(
                                      border: Border.all(color: Colors.white,width: 1),
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: Text((_userInfo['className']!=null ? _userInfo['className'] : '') ,
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setSp(11),
                                      fontWeight: FontWeight.w400,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                              Offstage(
                                offstage: _userInfo['teacherName'] ==null,
                                child: Container(
                                  margin: EdgeInsets.only(
                                      top: 5,
                                      left: 10
                                  ),
                                  padding: EdgeInsets.all(3),
                                  decoration: BoxDecoration(
                                      border: Border.all(color: Colors.white,width: 1),
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: Text("导师: "+(_userInfo['teacherName']!=null ? _userInfo['teacherName'] : ""),
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Medium',
                                      fontSize: ScreenUtil().setSp(11),
                                      fontWeight: FontWeight.w400,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    height: MediaQuery.of(context).size.height - ScreenUtil().setHeight(220),
                    child: Column(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(
                            bottom: ScreenUtil().setHeight(7.5),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              height: ScreenUtil().setHeight(50),
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15.5),
                                right: ScreenUtil().setWidth(15.5),
                                top: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(15),
                              ),
                              color: Colors.white,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Image.asset('assets/images/mine/icon_personal.png',
                                        width: ScreenUtil().setHeight(20),
                                        height: ScreenUtil().setHeight(20),
                                        fit: BoxFit.fill,
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(10),
                                        ),
                                        child: Text('个人资料',
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Regular',
                                            fontSize: ScreenUtil().setSp(14),
                                            fontWeight: FontWeight.w600,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                            height: 1.4,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Icon(Icons.navigate_next,
                                    size: ScreenUtil().setSp(20),
                                    color: Color.fromRGBO(133, 133, 133, 1),
                                  ),
                                ],
                              ),
                            ),
                            onPressed: () {
                              print('个人资料');
                              Navigator.push(context, MaterialPageRoute(builder: (context) => Personal(_userInfo,(u)=>setUser(u))));
                            },
                          ),
                        ),
                        Offstage(
                          offstage: Global.profile.userTypeEnum == 2,
                          child: Container(
                            margin: EdgeInsets.only(
                              bottom: ScreenUtil().setHeight(7.5),
                            ),
                            child: FlatButton(
                              padding: EdgeInsets.all(0),
                              child: Container(
                                width: MediaQuery.of(context).size.width,
                                height: ScreenUtil().setHeight(50),
                                padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15.5),
                                  right: ScreenUtil().setWidth(15.5),
                                  top: ScreenUtil().setWidth(15),
                                  bottom: ScreenUtil().setWidth(15),
                                ),
                                color: Colors.white,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Image.asset('assets/images/mine/icon_info.png',
                                          width: ScreenUtil().setHeight(20),
                                          height: ScreenUtil().setHeight(20),
                                          fit: BoxFit.fill,
                                        ),
                                        Container(
                                          margin: EdgeInsets.only(
                                            left: ScreenUtil().setWidth(10),
                                          ),
                                          child: Text('我的功课',
                                            style: TextStyle(
                                              fontFamily: 'PingFangSC-Regular',
                                              fontSize: ScreenUtil().setSp(14),
                                              fontWeight: FontWeight.w600,
                                              color: Color.fromRGBO(51, 51, 51, 1),
                                              height: 1.4,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Icon(Icons.navigate_next,
                                      size: ScreenUtil().setSp(20),
                                      color: Color.fromRGBO(133, 133, 133, 1),
                                    ),
                                  ],
                                ),
                              ),
                              onPressed: () {
                                Navigator.push(context, MaterialPageRoute(builder: (context) => MyShare()));
                              },
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            bottom: ScreenUtil().setHeight(7.5),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              height: ScreenUtil().setHeight(50),
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15.5),
                                right: ScreenUtil().setWidth(15.5),
                                top: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(15),
                              ),
                              color: Colors.white,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Image.asset('assets/images/mine/grzx_qchc.png',
                                        width: ScreenUtil().setHeight(20),
                                        height: ScreenUtil().setHeight(20),
                                        fit: BoxFit.fill,
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(10),
                                        ),
                                        child: Text('清除缓存',
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Regular',
                                            fontSize: ScreenUtil().setSp(14),
                                            fontWeight: FontWeight.w600,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                            height: 1.4,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Text(_cacheSizeStr,
                                    style: TextStyle(
                                      fontFamily: 'PingFangSC-Regular',
                                      fontSize: ScreenUtil().setSp(13),
                                      color: Color.fromRGBO(133, 133, 133, 1),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            onPressed: () {

                              showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                    return AlertDialog(
                                      contentPadding: EdgeInsets.all(0),
                                      actionsPadding: EdgeInsets.all(0),
                                      buttonPadding: EdgeInsets.all(0),
                                      insetPadding: EdgeInsets.all(0),
                                      content: Container(
                                        width: ScreenUtil().setWidth(300),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(
                                              width: ScreenUtil().setHeight(0.5),
                                              color: Color.fromRGBO(238, 238, 238, 1),
                                            ),
                                          ),
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Container(
                                              margin: EdgeInsets.only(
                                                top: ScreenUtil().setHeight(40.5),
                                                bottom: ScreenUtil().setHeight(32),
                                              ),
                                              child: Text('确定清除缓存？',
                                                style: TextStyle(
                                                  fontFamily: 'PingFangSC-Regular',
                                                  fontSize: ScreenUtil().setSp(14),
                                                  color: Color.fromRGBO(25, 28, 34, 1),
                                                  height: 1,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      actions: <Widget>[
                                        Container(
                                          width: ScreenUtil().setWidth(150),
                                          height: ScreenUtil().setHeight(40),
                                          decoration: BoxDecoration(
                                            border: Border(
                                              right: BorderSide(
                                                width: ScreenUtil().setHeight(0.5),
                                                color: Color.fromRGBO(238, 238, 238, 1),
                                              ),
                                            ),
                                          ),
                                          child: FlatButton(
                                            child: Text('取消',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Medium',
                                                fontSize: ScreenUtil().setSp(14),
                                                fontWeight: FontWeight.w600,
                                                color: Color.fromRGBO(102, 102, 102, 1),
                                                height: 1,
                                              ),
                                            ),
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ),
                                        Container(
                                          width: ScreenUtil().setWidth(150),
                                          height: ScreenUtil().setHeight(40),
                                          child: FlatButton(
                                            child: Text('确认',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Medium',
                                                fontSize: ScreenUtil().setSp(14),
                                                fontWeight: FontWeight.w600,
                                                color: Color.fromRGBO(214, 178, 128, 1),
                                                height: 1,
                                              ),
                                            ),
                                            onPressed: () {
                                              _clearCache();
                                              print('清除缓存');
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ),
                                      ],
                                    );
                                },
                              );
                            },
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            bottom: ScreenUtil().setHeight(7.5),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              height: ScreenUtil().setHeight(50),
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15.5),
                                right: ScreenUtil().setWidth(15.5),
                                top: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(15),
                              ),
                              color: Colors.white,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Image.asset('assets/images/mine/icon_info.png',
                                        width: ScreenUtil().setHeight(20),
                                        height: ScreenUtil().setHeight(20),
                                        fit: BoxFit.fill,
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(10),
                                        ),
                                        child: Text('关于我们',
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Regular',
                                            fontSize: ScreenUtil().setSp(14),
                                            fontWeight: FontWeight.w600,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                            height: 1.4,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Icon(Icons.navigate_next,
                                    size: ScreenUtil().setSp(20),
                                    color: Color.fromRGBO(133, 133, 133, 1),
                                  ),
                                ],
                              ),
                            ),
                            onPressed: () {
                              print('版本信息');
                              Request().post<Map<String,dynamic>>("/multiapi/open/c205v_about").then((response){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => AboutUs(response.data['content'])));
                              });
                            },
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                            bottom: ScreenUtil().setHeight(7.5),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              height: ScreenUtil().setHeight(50),
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(15.5),
                                right: ScreenUtil().setWidth(15.5),
                                top: ScreenUtil().setWidth(15),
                                bottom: ScreenUtil().setWidth(15),
                              ),
                              color: Colors.white,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                     Icon(Icons.library_books,color: Colors.grey,),
                                      Container(
                                        margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(10),
                                        ),
                                        child: Text('隐私协议',
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Regular',
                                            fontSize: ScreenUtil().setSp(14),
                                            fontWeight: FontWeight.w600,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                            height: 1.4,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  Icon(Icons.navigate_next,
                                    size: ScreenUtil().setSp(20),
                                    color: Color.fromRGBO(133, 133, 133, 1),
                                  ),
                                ],
                              ),
                            ),
                            onPressed: () {
                              print('版本信息');
                              Request().post<Map<String,dynamic>>("/multiapi/open/c205v_about").then((response){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => Protocol(()=>(){},readOnly: true,)));
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            AppBar(
              brightness: Brightness.light,
              title: Text('个人中心',
                style: TextStyle(
                  fontFamily: 'PingFangSC-Medium',
                  fontSize: ScreenUtil().setSp(16),
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                  height: 1,
                ),
              ),
              centerTitle: true,
              backgroundColor: Colors.transparent,
              elevation: 0,
            ),
          ],
        ),
      ),
    );
  }
  setUser(u){
    setState(() {
      _userInfo = u;
    });
  }
}